package playgame;

import java.io.*;
import javax.sound.midi.*;

/**
 * Handles playing midifiles.
 * 
 * @author Bomberman Crew 20(C)09
 *
 */

public class Midi {
	
	String navn;
	File midiFil;
	Sequencer sequence;
	
	/**
	 * Constructor
	 * @param navn
	 * takes a String argument as the name of the midi-file without the .mid part
	 */
	Midi(String navn){
		this.navn = navn;
		this.midiFil = new File("sounds/" + navn + ".midi");
	}
	/*
	 * Plays the midifile once
	 */
	public void playOnce(){
		try{
			sequence = MidiSystem.getSequencer();
			sequence.setSequence(MidiSystem.getSequence(midiFil));
			sequence.open();
			sequence.start();
        } catch(MidiUnavailableException mue) {
            System.out.println("Midi device unavailable!");
        } catch(InvalidMidiDataException imde) {
            System.out.println("Invalid Midi data!");
        } catch(IOException ioe) {
            System.out.println("I/O Error!");
        } 
		}
	/**
	 * Terminates the playing midifile when finished
	 */
	public void stop(){
		while(true) {
            if(sequence.isRunning()) {
                try {
                    Thread.sleep(1000); // Check every second
                } catch(InterruptedException ignore) {
                    break;
                }
            } else {
                break;
            }
        }
        
        sequence.stop(); // Close the MidiDevice & free resources
        sequence.close(); // Close the MidiDevice & free resources
        
	}
	
	/**
	 * plays a midi file sent to the constructor once
	 * 
	 */
	public void playMidi() {
		Midi test = new Midi(this.navn);
		test.playOnce();
		test.stop();
	}
	
	
}
